import { computed, ref } from "vue"

// 店铺类型接口
export interface StoreType {
  id: string
  name: string
  createdAt: string
  linkedPersonas: number
}

// 新增/编辑店铺类型数据接口
export interface CreateStoreTypeData {
  name: string
}

export function useStoreTypeManagement() {
  // 页面状态
  const loading = ref(false)
  const searchKeyword = ref("")
  const showCreateDialog = ref(false)
  const currentEditStoreType = ref<StoreType | null>(null)

  // 店铺类型数据
  const storeTypes = ref<StoreType[]>([
    {
      id: "ST001",
      name: "餐饮美食",
      createdAt: "2024-01-15",
      linkedPersonas: 2
    },
    {
      id: "ST002",
      name: "零售商店",
      createdAt: "2024-01-20",
      linkedPersonas: 1
    },
    {
      id: "ST003",
      name: "美容美发",
      createdAt: "2024-02-01",
      linkedPersonas: 1
    },
    {
      id: "ST004",
      name: "健身运动",
      createdAt: "2024-02-10",
      linkedPersonas: 0
    },
    {
      id: "ST005",
      name: "教育培训",
      createdAt: "2024-02-15",
      linkedPersonas: 0
    }
  ])

  // 搜索过滤
  const filteredStoreTypes = computed(() => {
    if (!searchKeyword.value.trim()) {
      return storeTypes.value
    }

    const keyword = searchKeyword.value.toLowerCase()
    return storeTypes.value.filter(storeType =>
      storeType.name.toLowerCase().includes(keyword)
      || storeType.id.toLowerCase().includes(keyword)
    )
  })

  // 头部按钮配置
  const headerButtons = computed(() => [
    {
      text: "新增店铺类型",
      icon: "Plus",
      type: "primary" as const,
      onClick: openCreateDialog
    }
  ])

  // 打开新增弹窗
  const openCreateDialog = () => {
    currentEditStoreType.value = null
    showCreateDialog.value = true
  }

  // 打开编辑弹窗
  const openEditDialog = (storeType: StoreType) => {
    currentEditStoreType.value = storeType
    showCreateDialog.value = true
  }

  // 关闭弹窗
  const closeDialog = () => {
    showCreateDialog.value = false
    currentEditStoreType.value = null
  }

  // 处理新增/编辑店铺类型
  const handleCreateStoreType = async (data: CreateStoreTypeData) => {
    try {
      loading.value = true

      if (currentEditStoreType.value) {
        // 编辑模式
        console.log("编辑店铺类型:", { id: currentEditStoreType.value.id, ...data })

        // TODO: 调用编辑API
        // await updateStoreType(currentEditStoreType.value.id, data)

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))

        // 更新本地数据
        const index = storeTypes.value.findIndex(item => item.id === currentEditStoreType.value!.id)
        if (index !== -1) {
          storeTypes.value[index] = {
            ...storeTypes.value[index],
            name: data.name
          }
        }

        ElMessage.success("店铺类型更新成功")
      } else {
        // 新增模式
        console.log("新增店铺类型:", data)

        // TODO: 调用新增API
        // const newStoreType = await createStoreType(data)

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))

        // 生成新的店铺类型
        const newStoreType: StoreType = {
          id: `ST${String(storeTypes.value.length + 1).padStart(3, "0")}`,
          name: data.name,
          createdAt: new Date().toISOString().split("T")[0],
          linkedPersonas: 0
        }

        // 添加到列表
        storeTypes.value.unshift(newStoreType)

        ElMessage.success("店铺类型创建成功")
      }

      // 关闭弹窗
      closeDialog()
    } catch (error) {
      console.error("操作失败:", error)
      ElMessage.error("操作失败，请重试")
    } finally {
      loading.value = false
    }
  }

  // 处理删除店铺类型
  const handleDeleteStoreType = async (storeType: StoreType) => {
    // 检查是否有关联人设
    if (storeType.linkedPersonas > 0) {
      ElMessage.warning("该店铺类型已关联人设，无法删除")
      return
    }

    try {
      await ElMessageBox.confirm(
        `确定要删除店铺类型"${storeType.name}"吗？`,
        "删除确认",
        {
          confirmButtonText: "确定删除",
          cancelButtonText: "取消",
          type: "warning",
          confirmButtonClass: "el-button--danger"
        }
      )

      loading.value = true

      console.log("删除店铺类型:", storeType.id)

      // TODO: 调用删除API
      // await deleteStoreType(storeType.id)

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300))

      // 从列表中移除
      const index = storeTypes.value.findIndex(item => item.id === storeType.id)
      if (index !== -1) {
        storeTypes.value.splice(index, 1)
      }

      ElMessage.success("删除成功")
    } catch (error) {
      if (error !== "cancel") {
        console.error("删除失败:", error)
        ElMessage.error("删除失败，请重试")
      }
    } finally {
      loading.value = false
    }
  }

  // 刷新数据
  const refreshData = async () => {
    try {
      loading.value = true

      console.log("刷新店铺类型数据")

      // TODO: 调用API获取数据
      // const data = await getStoreTypes()
      // storeTypes.value = data

      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 800))
    } catch (error) {
      console.error("数据加载失败:", error)
      ElMessage.error("数据加载失败，请重试")
    } finally {
      loading.value = false
    }
  }

  // 组件挂载时加载数据
  onMounted(() => {
    // 由于使用模拟数据，这里不需要调用refreshData
    // refreshData()
  })

  return {
    // 状态
    loading,
    searchKeyword,
    showCreateDialog,
    currentEditStoreType,

    // 数据
    storeTypes,
    filteredStoreTypes,

    // 配置
    headerButtons,

    // 方法
    openCreateDialog,
    openEditDialog,
    closeDialog,
    handleCreateStoreType,
    handleDeleteStoreType,
    refreshData
  }
}

// 工具函数 - 格式化日期
export function formatDate(dateString: string): string {
  return new Date(dateString).toLocaleDateString("zh-CN")
}

// 工具函数 - 生成店铺类型ID
export function generateStoreTypeId(existingIds: string[]): string {
  const numbers = existingIds
    .map(id => Number.parseInt(id.replace("ST", ""), 10))
    .filter(num => !Number.isNaN(num))

  const maxNumber = Math.max(...numbers, 0)
  return `ST${String(maxNumber + 1).padStart(3, "0")}`
}
